<template>
  <div>
    <base-layout :visibleContent="false">
      <template #searchPanel>
        <el-row>
          <el-radio-group v-model="tabs">
            <el-radio-button label="return">退货基础信息</el-radio-button>
            <el-radio-button label="price" v-if="priceId"
              >采购信息</el-radio-button
            >
          </el-radio-group>
        </el-row>
      </template>
    </base-layout>
    <PurchaseRecordsDetail v-if="showPrice" :id="priceId" />
    <base-layout
      :dialogVisible="dialogVisible"
      :dialogTitle="dialogTitle"
      @dialog-close="dialogClose"
      :visibleContent2="true"
      :visibleContent3="true"
      v-if="showReturn"
    >
      <template #searchPanel>
        <el-form
          :inline="true"
          ref="fromdata1"
          :model="fromdata"
          :rules="rules"
          label-width="130px"
          label-position="right"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="退货编号:" prop="returnCode">
                <el-input
                  clearable
                  readonly="readonly"
                  v-model="fromdata.returnCode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="退货门店:" prop="inStoreId">
                <Job-shop
                  v-model="fromdata.storeId"
                  :defaultStoreId="true"
                  placeholder="采购门店"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="退货供应商:" prop="returnSupplierId">
                <el-select
                  clearable
                  style="width: 200px"
                  v-model="fromdata.returnSupplierId"
                  placeholder="退货供应商"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.supplierName"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="退货类型:" prop="returnType">
                <el-select
                  clearable
                  style="width: 200px"
                  v-model="fromdata.returnType"
                >
                  <el-option
                    v-for="item in dict['退货类型']"
                    :key="item.index"
                    :value="item.value"
                    :label="item.text"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="单据日期:" prop="receiptsTime">
                <el-date-picker
                  value-format="yyyy-MM-dd hh:mm:ss"
                  v-model="fromdata.receiptsTime"
                  type="datetime"
                  disabled="disabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购单号:" prop="purchaseCode">
                <el-input
                  clearable
                  v-model.number="fromdata.purchaseCode"
                  @blur="findSourceCode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商联系人:">
                <el-input clearable v-model="fromdata.supplierUserName" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商联系方式:">
                <el-input clearable v-model.number="fromdata.supplierPhone" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="退货备注:" prop="remark">
                <el-input
                  type="textarea"
                  :rows="6"
                  placeholder=""
                  v-model="fromdata.remark"
                  style="width: 600px"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>

      <template #contentPanel>
        <el-form
          :inline="true"
          ref="fromdata2"
          :model="fromdata"
          :rules="rules"
          label-width="90px"
          label-position="right"
          class="insuranceForm"
        >
          <el-row>
            <el-col :span="2">退货负责人员</el-col>
          </el-row>
          <el-divider content-position="center"></el-divider>
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="退货负责人:"
                label-width="120px"
                prop="userName"
              >
                <el-input
                  clearable
                  v-model="fromdata.userName"
                  @focus="employeeFocus"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系电话:" prop="phone" label-width="120px">
                <el-input clearable v-model.number="fromdata.phone" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>

      <template #contentPanel2>
        <el-form
          :inline="true"
          ref="fromdata"
          :show-message="false"
          :hide-required-asterisk="true"
          :model="fromdata"
          :rules="rules"
          label-width="90px"
          label-position="right"
          class="insuranceForm"
        >
          <el-row>
            <el-col :span="20">退货配件列表</el-col>
            <!-- <el-col :span="2">
              <el-button
                v-if="priceId"
                icon="el-icon-plus"
                type="primary"
                @click="addInventory"
                >从采购单中选择退货配件</el-button
              >
              <el-button v-else icon="el-icon-plus" type="primary" @click="addInventory"
                >从库存中中选择退货配件</el-button
              >
            </el-col> -->
          </el-row>
          <el-divider content-position="center"></el-divider>
          <el-row>
            <data-table
              :value="fromdata.partsList"
              :total-count="fromdata.partsList.length"
              :has-action="true"
              :table-column-attributes="tableColumnAttributes"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :width="160"
              :localPage="true"
            >
              <template #action="{ row }">
                <i
                  class="el-icon-delete"
                  title="删除"
                  style="color: red; margin-left: 20px; cursor: pointer"
                  @click="deleteLochost(row)"
                ></i>
              </template>
              <template #allNum>
                <el-col :span="8" v-if="allMount">
                  <span
                    style="line-height: 10px; text-align: left; color: #606266"
                    >退货配件总金额：<span style="color: #f40; font-size: 20px"
                      >￥{{ allMount }}</span
                    ></span
                  >
                </el-col>
                <el-col :span="8" v-if="fromdata.freePrice">
                  <span
                    style="line-height: 10px; text-align: left; color: #606266"
                    >退货配件总优惠金额：<span
                      style="color: #f40; font-size: 20px"
                      >￥{{ fromdata.freePrice }}</span
                    ></span
                  >
                </el-col>
                <el-col :span="8" v-if="allMount1">
                  <span
                    style="line-height: 10px; text-align: left; color: #606266"
                    >配件总数：<span style="color: #f40; font-size: 20px">{{
                      allMount1
                    }}</span></span
                  >
                </el-col>
              </template>
            </data-table>
          </el-row>
        </el-form>
      </template>
      <template #contentPanel3>
        <el-row>
          <el-col :span="24" align="right" justify="center">
            <el-col :span="24">
              <span style="line-height: 10px; text-align: left; color: #606266"
                >退货总金额：<span
                  style="color: #f40; font-size: 20px"
                  v-if="allMount"
                  >￥{{ allMount }}</span
                ></span
              >
            </el-col>
            <el-col :span="24" style="margin-top: 20px">
              <el-button type="success" @click="saveUpdate"
                >新建退货单</el-button
              >
            </el-col>
          </el-col>
        </el-row>
      </template>
      <template #dialog>
        <SelectAccessories
          :storageId="fromdata.storeId"
          v-if="showSelect"
          :supplierId="fromdata.purchaseSupplierId"
          @partsList="partsList"
          :partsIds="partsIds"
        />
        <EmployeeTable
          v-if="showEmployeeTable"
          @roleIdListSelectCheck="employeListSelectCheck"
          :checkList="[fromdata.manageUserName]"
        />
      </template>
    </base-layout>
  </div>
</template>
<script>
import baseMixin from '@/mixins/base'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import {
  add,
  update,
  getFindById,
  getPurchaseCode,
  findSourceCode,
} from '@/api/after-sale/purchaseManage/purchaseReturn'
import { findByStore } from '@/api/after-sale/storehouseManage/warehouseManage'
import EmployeeTable from '../../systemManage/store/components/EmployeeTable'
import SelectAccessories from '@/components/SelectAccessories/index' //导入组件
import { getSupplierByStorId } from '@/api/after-sale/systemManage/supplier'
import PurchaseRecordsDetail from './components/purchaseRecordsDetail'
import store from '@/store'
export default {
  components: {
    EmployeeTable,
    SelectAccessories,
    PurchaseRecordsDetail,
  },
  mixins: [
    baseMixin({
      addData: add,
      updateData: update,
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  watch: {
    'fromdata.partsList': {
      handler(value) {
        this.sumAllMount()
      },
      deep: true,
    },
    'fromdata.storeId': function (value) {
      if (value) {
        this.getSupplierByStorId(value)
      } else {
        this.getSupplierByStorId(store.state.user.entryStore)
      }
    },
    'fromdata.returnSupplierId': function (value) {
      if (value) {
        this.supplierList.forEach((e) => {
          if (e.id == value) {
            this.fromdata.supplierUserName = e.contactName
            this.fromdata.supplierPhone = e.contactPhone
          }
        })
      }
    },
    tabs: function (value) {
      if (value === 'return') {
        this.showReturn = true
        this.showPrice = false
      } else if (value === 'price') {
        this.showReturn = false
        this.showPrice = true
      }
    },
  },
  data() {
    return {
      fromdata: {
        id: '',
        userType: false,
        partsList: [],
        freePrice: null,
        purchaseCode: null,
        receiptsTime: parseTimeToYMDHMS(new Date()),
        returnSupplierId: null,
        userName: null,
      },
      tabs: 'return',
      rules: {
        storeId: [
          { required: true, message: '请选择退货门店', trigger: 'change' },
        ],
        returnSupplierId: [
          { required: true, message: '请选择退货供应商', trigger: 'change' },
        ],
        returnType: [
          { required: true, message: '请选择退货类型', trigger: 'change' },
        ],
        receiptsTime: [
          { required: true, message: '请选择单据日期', trigger: 'change' },
        ],
        supplierUserName: [
          { required: true, message: '请输入供应商联系人', trigger: 'bulr' },
        ],
        supplierPhone: [
          { required: true, message: '请输入供应商联系方式', trigger: 'bulr' },
        ],
        userName: [
          { required: true, message: '请选择退货负责人', trigger: 'change' },
        ],
      },
      allMount: null,
      allMount1: null,
      showReturn: true, // 展示退货基本信息
      showPrice: false, // 展示采购信息
      priceId: null, // 采购主键id
      dict: [],
      partsIds: [], // 采购单号查询得配件id集合
      showSelect: false, // 是否展示配件组件
      showEmployeeTable: false, //  是否展示员工组件
      supplierList: [],
      tableColumnAttributes: [
        { name: '配件编号', value: 'partsCode', type: 'text' },
        { name: '配件名称', value: 'partsName', type: 'text' },
        { name: '配件类别', value: 'partsType', type: 'text' },
        { name: '配件单位', value: 'partsUnit', type: 'text' },
        {
          name: '退货数量',
          value: 'returnNum',
          type: 'inputNumber',
          action: function (row) {
            row.amount = (
              row.returnPrice * row.returnNum -
              row.freePrice
            ).toFixed(2)
          },
        },
        {
          name: '采购单价',
          value: 'returnPrice',
          type: 'text',
        },
        { name: '总金额', value: 'amount', type: 'text' },
        {
          name: '优惠金额',
          value: 'freePrice',
          type: 'inputNumber',
          action: function (row) {
            row.amount = (
              row.returnPrice * row.returnNum -
              row.freePrice
            ).toFixed(2)
          },
        },
      ],
    }
  },
  methods: {
    // 动态计算表格总和
    sumAllMount() {
      this.allMount = null
      this.allMount1 = null
      this.fromdata.freePrice = null
      this.fromdata.partsList.forEach((e) => {
        if (e.amount) {
          this.allMount += Number.parseFloat(e.amount)
        }
        if (e.returnNum) {
          this.allMount1 += Number.parseInt(e.returnNum)
        }
        if (e.freePrice) {
          this.fromdata.freePrice += Number.parseInt(e.freePrice)
        }
      })
      this.allMount = this.allMount.toFixed(2)
    },
    // 根据来源单号查询配件列表
    async findSourceCode() {
      if (!this.fromdata.returnType) {
        this.$message.warning('请选择退货类型')
        return
      }
      if (this.fromdata.purchaseCode) {
        let { data } = await findSourceCode(
          this.fromdata.returnType,
          this.fromdata.purchaseCode
        )
        data.carPartsList.forEach((e) => {
          e.returnNum = e.purchaseNum
          e.returnPrice = e.purchasePrice
          e.num = e.purchaseNum
        })
        this.fromdata.partsList = data.carPartsList
        this.priceId = data.purchaseId
        this.fromdata.storeId = data.storeId
        this.fromdata.returnSupplierId = data.supplierId
        this.fromdata.supplierUserName = data.supplierUserName
        this.fromdata.supplierPhone = data.supplierPhone
      }
    },
    //删除临时配件
    deleteLochost(row) {
      this.fromdata.partsList = this.fromdata.partsList.filter(
        (e) => e.id != row.id
      )
    },
    // 打开配件选择
    addInventory() {
      this.showSelect = true
      this.showEmployeeTable = false
      this.handleDataInsert('配件选择')
    },
    // 选择配件
    partsList(value) {
      if (value.length > 0) {
        value.forEach((e) => {
          let index = true
          this.fromdata.partsList.forEach((g) => {
            if (e.id === g.id) {
              index = false
            }
          })
          if (index) {
            let { ...data } = {
              ...e,
              partsUnit: e.unit,
              partsId: e.id,
              partsType: e.partsDictValue,
              returnPrice: e.purchasePrice,
            }
            this.fromdata.partsList.push(data)
          }
        })
      }
      this.dialogClose()
    },
    //打开员工选择列表
    employeeFocus() {
      this.showSelect = false
      this.showEmployeeTable = true
      this.handleDataInsert('管理人员列表')
    },
    //员工选择
    employeListSelectCheck(select) {
      this.fromdata.userName = select[0].userName
      this.fromdata.phone = select[0].phone
      this.fromdata.userId = select[0].id
      this.dialogClose()
    },
    saveUpdate() {
      this.$refs['fromdata1'].validate((valid) => {
        this.$refs['fromdata2'].validate((valid1) => {
          if (valid && valid1) {
            this.handleDataUpdate(this.fromdata)
            this.closeRouter('/partsStock/purchaseManage/purchaseReturn')
          }
        })
      })
    },
    async detail(id) {
      let { data } = await getFindById(id)
      this.fromdata = data
      this.findSourceCode()
    },
    async getPurchaseCode() {
      let { data } = await getPurchaseCode()
      this.fromdata.returnCode = data
    },
    // 获取供应商
    async getSupplierByStorId(storeId) {
      let { data } = await getSupplierByStorId(storeId, '配件供应商')
      this.supplierList = data
    },
  },
  mounted() {
    this.dict = getDict(['退货类型'])
    this.getSupplierByStorId(store.state.user.entryStore)
    let id = this.$route.query.id
    let type = this.$route.query.type
    if (id) {
      if (type) {
        this.fromdata.purchaseCode = id
        this.fromdata.returnType = '采购退货'
        this.findSourceCode()
        this.getPurchaseCode()
      } else {
        this.fromdata.id = id
        this.detail(id)
      }
    } else {
      this.getPurchaseCode()
    }
  },
}
</script>
<style lang="scss" scoped></style>
